import { useEffect, useState } from 'react';
import { Spin, App } from 'antd';
import { useDispatch } from 'react-redux';

import { customSetTimeout } from '@/utils';
import { getWxPayQrCode, getWxPayStatus } from '@/service/pay';

import styles from './index.module.scss';

const STATUS = {
    '0': '待支付',
    '1': '支付成功',
    '2': '支付失败',
};
const WxQrCode = (props) => {
    const initState = () => ({
        loading: true,
        url: '',
        urlExpiration: false,
        errorMsg: '',
        status: '',
    });
    const [state, setState] = useState(initState);
    const dispatch = useDispatch();
    const {message} = App.useApp();
    const { payInfo={} } = props;
    const {price, ...rest} = payInfo || {};

    // 请求二维码，成功后开启轮询，判断二维码是否被扫、是否过期
    const initQrImage = () => {
        setState(o => ({...o, loading: true, urlExpiration: false, errorMsg: ''}));

        let formData = new FormData();
        formData.append('type', 1);
        for(let key in rest) {
            formData.append(key, rest[key]);
        }
        getWxPayQrCode(formData).then(response => {
            setState(o => ({...o, loading: false}));

            if(OK_CODE === response?.code) {
                let data = response.data || {};
                setState(o => ({...o, url: data?.schema || ''}));

                data?.orderId && loopQrImage(data?.orderId);
            }else{
                message.warning(response?.msg || response?.message || '失败');
                setState(o => ({...o, errorMsg: '请求异常，请重试'}));
            }
        }).catch(e => {
            setState(o => ({...o, loading: false, errorMsg: '请求异常，请重试'}));
            message.error(e?.msg || e?.message || '失败');
        });
    };

    // 轮询二维码
    const loopQrImage = (orderId='') => {
        // 轮询是否扫码
        let count = 0;

        if(!orderId) return;

        window.loopHandler && window.loopHandler();
        window.loopHandler = customSetTimeout(() => {
            if(count < 299) {
                count++;

                getWxPayStatus({orderId}).then(response => {
                    if(OK_CODE === response?.code) {
                        let status = response?.data?.status || '';

                        if([1,2].includes(status)) { // 0待支付 1支付成功 2失败
                            message.destroy();
                            window.loopHandler();
                            count = 1;
                            props.callback(status);
                        }
                    }
                }).catch(e => {console.log(e);});
            }else{
                window.loopHandler();
                count = 1;

                setState(o => ({...o, urlExpiration: true}));
            }
        }, 3000);
    };

    // 重新获取二维码
    const refresh = () => {
        initQrImage();
    };

    // 组件加载时请求二维码地址
    useEffect(() => {
        initQrImage();

        return () => {
            window.loopHandler && window.loopHandler();
        };
    }, []);

    return (
        <div className={styles['container']}>
            <div className={styles['img']}>
                { state.url ? <img src={state.url} alt={WEB_NAME} /> : null }
                {
                    state.urlExpiration || state.errorMsg ?
                        <div className={styles['url-expiration']} onClick={refresh}>
                            <p>{state.errorMsg || '二维码已失效'}</p>
                            <button>点击刷新</button>
                        </div>
                        :
                        null
                }

                { state.loading ? <div className={styles['loading']}><Spin/></div> : null}
            </div>
        </div>
    )
}

export default WxQrCode;
